<?php
namespace interface\v1;
/*
*出差申请接口类
*/

use verify;

class bussinessTripAppClass extends index {
    private const table = 'bussiness_trip';
    private const page = 'bussinessTrip';
    private const title = '出差申请';
    public array $stateOption = ['草稿','审核中','已通过'];
    /*查询条件*/
    public function search(){
        $this->code = 1;
        //类型
        //查询条件
        $data['result'] = array(
            //状态
            "stateOption" => $this->stateOption,
            "timeOption"=>$this->timeOption,
            'travelWay'=>explode('，',para('travelWay')),
            'feeOption'=>explode('，',para('tripFeeType')),
        );
        //返回
        $this->resp['data'] = $data;
    }
    /*列表页*/
    public function list()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            "state" => $this->post('state'),//审批状态
        );
        //初始化
        $and ='';
        if ($this->post('keyword')) {
            $and .= " and (reason like '%".$this->post('keyword')."%' or orderNo like '%".$this->post('keyword')."%')";
        }
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime,field: 'startTime');
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startTime desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'orderNo'=>$array['orderNo'],
                "startTime" => $array['startTime'],//开始时间
                "endTime" => $array['endTime'],//结束时间
                "reason" => $array['reason'],//补卡事由
                "state" => $array['state'],//状态
                'time'=>date('m/d',strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }
    /**
     * 获取员工ID一维数组
     */
    public static function returnStidCollection($array): array
    {
        return array_column(array_filter($array, function ($val) {
            return $val;
        }), 'id');
    }
    public function commitEdit(){
        $id = $this->post('id') ?: self::getId();
        $children = (array)json_decode($_POST['children'],true);
        //赋值
        $field = array(
            "startTime" => $this->post('startTime'),
            "endTime" => $this->post('endTime'),
            "reason" => $this->post('reason'),//备注
            "staffId" => $this->post('staffId'),
            'selector'       => $_POST['member']?implode(',',self::returnStidCollection(json_decode($_POST['member'],true))):'',//员工选择器
            'member'=> $_POST['member']?implode(',',self::returnStidCollection(json_decode($_POST['member'],true))):'',//员工选择器
            "destination" => $this->post('destination'),
            "goWay" => $_POST['goWay']?:[],
            "returnWay" =>$_POST['returnWay']?:[],
            "isTicket" => $this->post('isTicket')=='是'?1:0,
            "isHotel" => $this->post('isHotel')=='是'?1:0,
            "isAdvance" => $this->post('isAdvance')=='预支'?1:0,
            "fee" => $this->post('fee'),
        );
        $annotation = [
            "startTime" => '出差时间',
            "endTime" => '出差时间',
            "staffId" => '出差人',
            "destination" => '目的地',
            "goWay" => '出行方式',
            "returnWay" => '出行方式',
            "reason" => '出差事由',
        ];
        $rules = [
            'startTime' => 'required',
            'endTime' => 'required',
            "staffId" => 'required',
            "destination" => 'required',
            "goWay" => 'required',
            "returnWay" => 'required',
            'reason' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        }elseif ($field['startTime'] > $field['endTime']) {
            $this->resp['warn'] = "结束时间不得小于开始时间";
        } elseif (sqlNum(self::table, " staffId = '" . $field['staffId'] . "' and startTime < '$field[endTime]' and endTime > '$field[startTime]' and id != '" . $id . "' ") > 0) {
            $this->resp['warn']= "与其他出差时间存在交叉";
        } elseif($info['id'] && $info['state'] !='草稿'){
            $this->resp['warn'] = '不是草稿状态，暂不能编辑';
        }else{
            $this->startTrans();
            if (empty($info['id'])) {
                $userNo = self::generateCode(self::page,[
                    'prefix' => 'CCSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo, 'state' => '草稿', 'deptName' => $department['name'], 'stid' => self::$stid));
                $json['warn'] = static::insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            $idArr = [];
            if (is_array($children)){
                foreach ($children as $array){
                    $mx = query(self::table.'_budget',"id = '$array[id]'");
                    if (!empty($mx['id'])){
                        $mxId = $mx['id'];
                        $warn = static::update(array(
                            'table'=>self::table.'_budget',
                            'field'=>array(
                                'feeType'=>$array['feeType'],
                                'money'=>$array['money'],
                            ),
                            'where'=>"id = '$mx[id]'"
                        ));
                    }else{
                        $mxId = self::getId();
                        $warn = static::insert(array(
                            'table'=>self::table.'_budget',
                            'field'=>array(
                                'id'=>$mxId,
                                'orderId'=>$id,
                                'feeType'=>$array['feeType'],
                                'money'=>$array['money'],
                            )
                        ));
                    }
                    $idArr[] = $mxId;
                    if (!in_array($warn, array("新增成功", "更新成功"))) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                $this->commitTrans();
                delete(array('table'=>self::table.'_budget','where'=>"id not in ('".implode("','",$idArr)."') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                $this->resp['data']['id'] = $id;
                $this->resp['warn'] = $json['warn'];
                //返回
                $this->code=1;
            }else{
                $this->rollback();
            }
        }
        resp:
    }
    /*详情页*/
    public function detail(){
        $id = $this->post('id');
        $info = query(self::table, "id = '" . $id . "'");
        if (empty($id)) {
            $this->resp['warn'] = "ID为空";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此出差记录";
        } else {
            //申请人
            $staff = query("staff", "stid = '$info[staffId]'");
            $flowName = in_array($info['state'], ['已通过', '审核成果', '成果确认']) ? '出差成果审核' : '出差申请';
            $audit = query('audit', "targetId = '$info[id]' and flowName = '$flowName'");
            $record = auditAppClass::auditRecord(self::table,$id,$flowName);
            $auditRecord = [];
            $active = 0;
            if ($record !==false){
                $auditRecord = $record['record'];
                $active = $record['active'];
            }
            $member=[];
            $staffArr = explode(',',$info['member']);
            $memberName = '';
            foreach ($staffArr as $stid){
                $member[]=[
                    'id'=>$stid,
                    'name'=>self::findStaff($stid)
                ];
                $memberName.=self::findStaff($stid).',';
            }
            $memberName = rtrim($memberName,',');
            $data['result']['info'] = [
                'id'=>$id,
                'flowName'=>'出差申请',
                'orderNo'=>$info['orderNo'],
                'staffName'=>$staff['name'],
                'staffId'=>$staff['stid'],
                'member'=>$member,
                'memberName'=>$memberName,
                'startTime'=>$info['startTime'],
                'destination'=>$info['destination'],
                'reason'=>$info['reason'],
                'endTime'=>$info['endTime'],
                'goWay'=>json_decode($info['goWay'],true),
                'returnWay'=>json_decode($info['returnWay'],true),
                'goWayName'=>implode(',',json_decode($info['goWay'],true)),
                'returnWayName'=>implode(',',json_decode($info['returnWay'],true)),
                'isHotel'=>$info['isHotel']?'是':'否',
                'isTicket'=>$info['isTicket']?'是':'否',
                'isAdvance'=>$info['isAdvance']?'预支':'不预支',
                'fee'=>$info['fee'],
                'startFactTime'=>$info['factStartTime'],
                'endFactTime'=>$info['factEndTime'],
                'achievement'=>$info['achievement'],
                'commitTime'=>$audit['commitTime'],
                'deptName'=>$info['deptName'],
                'state'=>$info['state'],
                'stid'=>$info['stid'],
                'flowState'=>$flowName,
                'role'=>auditAppClass::role(self::table,$id,$flowName),
                'auditRecord'=>$auditRecord,
                'active'=>$active,
                'isResult'=>$flowName=='出差申请'?0:1,
            ];
            $data['result']['list']=[];
            $all = find(array('table'=>self::table.'_budget',"where"=>"orderId = '$id' order by list asc"));
            foreach ($all['array'] as $array){
                $data['result']['list'][] = [
                    'id'=>$array['id'],
                    'feeType'=>$array['feeType'],
                    'money'=>$array['money'],
                ];
            }
            $data['result']['attachFile']=[];
            $all = find(array('table'=>'file',"where"=>"targetId = '$id' order by time asc"));
            foreach ($all['array'] as $file){
                $data['result']['attachFile'][] = [
                    'id'=>$file['id'],
                    'size'=>self::formatSize($file['size']),
                    'format'=>$file['format'],
                    'src'=>self::fillSrc($file['src']),
                    'name'=>$file['name'],
                    'url' => self::fillSrc($file['src']),
                ];
            }
            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
    }

    /**
     * 编辑成果页面
     */
    public function editResult()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (empty($info['id'])) {
            $this->resp['warn'] = '未找到此出差记录';
        } else {
            $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
            $file = [];
            foreach ($attachFile['array'] as $array) {
                $file[] = [
                    'id' => $array['id'],
                    'name' => $array['name'],
                    'format' => $array['format'],
                    'size' => $array['size'],
                    'src' => self::fillSrc($array['src']),
                    'url' => self::fillSrc($array['src']),
                ];
            }
            $data['result'] = [
                'id' => $id,
                'startFactTime' => $info['factStartTime'],
                'endFactTime' => $info['factEndTime'],
                'result' => $info['achievement'],
                'attachFile' => $file
            ];
            $this->code = 1;
            $this->resp['data'] = $data;
        }

    }

    public function commitResult()
    {
        $id = $this->post('id');
        //附件
        $fileIdArr = (array)json_decode($_POST['fileId'],true);
        //赋值
        $field = array(
            "factStartTime" => $this->post('startTime'),
            "factEndTime" => $this->post('endTime'),
            "achievement" => $this->post('result'),//备注
        );
        $annotation = [
            "factStartTime" => '实际出差时间',
            "factEndTime" => '实际出差时间',
            "achievement" => '出差成果',
        ];
        $rules = [
            'factStartTime' => 'required',
            'factEndTime' => 'required',
            'achievement' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        } elseif (strtotime($field['factEndTime']) < strtotime($field['factStartTime'])) {
            $this->resp['warn'] = "结束时间不得小于开始时间";
        } elseif (sqlNum(self::table, " staffId = '" . $this->control['stid'] . "' and factStartTime < '$field[factEndTime]' and factEndTime > '$field[factStartTime]' and id != '" . $id . "' ") > 0) {
            $this->resp['warn'] = "与其他实际出差时间存在交叉";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = '未找到此出差记录';
        }elseif($info['state'] !='已通过'){
            $this->resp['warn'] = '此出差申请不是已通过状态，不能编辑成果';
        } else {
            $this->resp['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
        }
        if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            }
            //添加日志
            $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了" . self::title . "成果ID：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //返回
            $this->code = 1;
        }
        resp:
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的".self::title;
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此".self::title."不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //删除audit表记录
                delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                //删除待办事项
                delete(array("table" => "backlog","where" => " typeId = '$id' "));
                //删除审批记录
                delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                //删除消息提醒
                delete(array("table" => "message","where" => " typeId = '$id' "));
                $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                foreach ($all['array'] as $val){
                    fileDelete($val['src']);
                    delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                }
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }
}